<template>
  <div class="json-editor">
    <textarea ref="textarea" style="width: 100%;"></textarea>
    <el-divider content-position="left">操作</el-divider>
    <div class="flex-space-between">
      <el-button color="#626aef" :dark="false" plain @click="formatSql"><SvgIcon iconName="icon--SQLzhichi"></SvgIcon>格式化sql</el-button>
      <el-button color="#626aef" :dark="false" plain @click="run"><SvgIcon iconName="icon-bianzu"></SvgIcon>运行</el-button>
    </div>
  </div>
</template>

<script setup>
import 'codemirror/theme/ambiance.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint.css'
import CodeMirror from 'codemirror'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/mode/sql/sql'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/sql-hint'
import { format } from 'sql-formatter'
import API from '@/components/api/form_generator'

defineOptions({
  name: 'codeMirror',
  inheritAttrs: false
})

const props = defineProps({
  value: {
    type: String,
    required: true
  },
  height: {
    type: String,
    required: true
  },
  sqlStyle: {
    type: String,
    default: 'default'
  },
  readOnly: {
    type: [Boolean, String]
  }
})
const { value } = toRefs(props)

const textarea = ref(null)

const editor = ref(null)

onMounted(() => {
  editor.value = CodeMirror.fromTextArea(textarea.value, {
    value: value.value,
    mode: 'text/x-mysql', // 选择对应代码编辑器的语言，我这边选的是数据库，根据个人情况自行设置即可
    lineNumbers: true, // 是否在编辑器左侧显示行号
    lint: true,
    matchBrackets: true, // 括号匹配
    lineWrapping: true,
    tabSize: 2, // 缩进格式
    styleActiveLine: true, // 高亮选中行
    cursorHeight: 0.9,
    // 替换主题这里需修改名称
    theme: 'solarized light',
    // 是否为只读,如果为"nocursor" 不仅仅为只读 连光标都无法在区域聚焦
    readOnly: false,
    extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
    hintOptions: { // 自定义提示选项
      tables: {
        users: ['name', 'score', 'birthDate'],
        countries: ['name', 'population', 'size']
      }
    }
  })
  editor.value.setSize('auto', 600)
  // 代码自动提示功能，记住使用cursorActivity事件不要使用change事件，这是一个坑，那样页面直接会卡死
  editor.value.on('inputRead', () => {
    editor.value.showHint()
  })
})

const formatSql = () => {
  /* （sql编辑器内容绑定content参数） 将sql内容进行格式后放入编辑器中*/
  const sqlcontent = editor.value.getValue()
  editor.value.setValue(format(sqlcontent))
  const cursor = editor.value.doc.getCursor()
  editor.value.setCursor(cursor)
}

const run = () => {
  API.getSQLForm({ 'sql': editor.value.getValue() }).then((result) => {
    console.log(result)
  })
}

// const setVal = () => {
//   // 清空SQL编辑器内容
//   editor.value.setValue('')
// }
</script>

<style lang="scss" scoped>
	.json-editor {
		height: 100%;
    box-sizing: border-box;
    .CodeMirror {
      font-size: 14px;
      font-weight: normal;
    }
    .cm-s-rubyblue span.cm-string {
      color: #F08047;
      }
    }
</style>

